import Taro, { Component } from '@tarojs/taro'
import { AtTabs, AtTabsPane } from 'taro-ui'
import { View, ScrollView } from '@tarojs/components'
import { DNavBar, DCarorder, DModal, DItemError } from '@/components'
import './carsalesorder.scss'
import http from '@/api'
import sdk from '@/common/sdk'
const conf = require('../../../config/conf')

export default class CarsalesorderBox extends Component {
  constructor(props) {
    super(props)
    this.state = {
      active: 0,
      isShow: false,
      item: {},
      obj1: {
        page: 1,
        limit: 10,
        orStage: 2
      },
      crmodal: '',
      modal1: '',
      scrollStyle: window.screen.availHeight,
      footerStatus: false,
      totalPage: 1,
      list: [],
    }
  }


  componentWillMount() {
    let { active = '', remark, id } = this.$router.params
    if (remark == 2) {
      // 确认退款回调
      http.drawOrder2({ orderId: id }).then(() => {
        Taro.navigateTo({
          url: `/pages/carsalesorder/carsalesorder?active=2`
        })
      })
      return
    }
    if (active) {
      this.handleClick(+active)
    } else {
      this.getSaleOrder()
    }
  }
  // 回调页面再次请求
  componentDidShow() {
    let { obj1, active } = this.state
    if (+active === 0) {
      obj1.page = 1
      obj1.orStage = 2
    } else if (+active === 1) {
      obj1.page = 1
      obj1.orStage = 3

    } else if (+active === 2) {
      obj1.page = 1
      obj1.orStage = 4
    } else if (active == 3) {
      // 确认退款列表
      this.pendingRefund()
    }
    this.setState({
      list: [],
      obj1
    }, () => {
      this.getSaleOrder()
    })
    sdk.setTitleInfo('售车订单')
  }

  getSaleOrder() {
    let { page, limit, orStage } = this.state.obj1
    let { totalPage, active } = this.state

    let orSaleId = ''
    if (localStorage.getItem('userInformation')) {
      let { dsfUserEntity = '' } = JSON.parse(localStorage.getItem('userInformation'))
      orSaleId = dsfUserEntity.userId
    }
    let obj = {
      page,
      limit,
      // orSaleId: orSaleId ||'1210110786093981905',//订单卖方id
      orSaleId: orSaleId,//订单卖方id
      orStage,  //tab状态
      sign: 1 // 买家0，卖家1
    }
    if (page > totalPage) {
      this.setState({
        footerStatus: true
      })
      return
    }
    http.getSaleOrder(obj).then(res => {
      if (!res) {
        return
      }
      let responseList = res.list;
      if (active === 0) {
        responseList = responseList.filter(item => item.orStatus === "21");
      }

      let { list } = this.state
      let _list = []
      if (page > 1) {
        _list = [...list, ...responseList]
      } else {
        _list = [...responseList]
      }
      this.setState({
        list: _list,
        totalPage: res.totalPage || 1
      }, () => {
      })
    })
  }

  handleClick(value) {
    let { obj1 } = this.state
    this.setState({
      list: []
    })
    // 待接单
    if (value == 0) {
      this.setState({
        obj1: {
          ...obj1,
          page: 1,
          orStage: 2
        }
      }, () => this.getSaleOrder())
    }

    // 上传合同
    if (value == 1) {
      this.setState({
        obj1: {
          ...obj1,
          page: 1,
          orStage: 3
        }
      }, () => this.getSaleOrder())
    }
    // 已完结
    if (value == 2) {
      this.setState({
        obj1: {
          ...obj1,
          page: 1,
          orStage: 4
        }
      }, () => this.getSaleOrder())
    }
    this.setState({
      active: value
    })
    if (value == 3) {
      this.pendingRefund()
    }
  }
  async pendingRefund() {
    const { list } = await http.pendingRefund()
    this.setState({
      list
    })
  }

  handlerprops(item) {
    let { id, orStatus } = item
    Taro.navigateTo({
      url: `/pages/itemdetail/saledetail?id=${id}&status=${orStatus}`
    })
  }
  onScroll = () => {
    this.setState({
      obj1: {
        ...this.state.obj1,
        page: this.state.obj1.page + 1
      }
    }, () => {
      this.getSaleOrder()
    })
  }
  onHandleFirst() {
  }
  //接受订单
  onhandleAccept(item, status) {
    let isShow = true
    this.setState({
      isShow,
      item,
      crmodal: status,
      modal1: '您确认接受订单吗？'
    })
  }

  confirmSaleOrder(orderId) {
    http.acceptSaleOrder({ orderId: orderId }).then((res) => {
      if (!res) {
        return
      }
      Taro.navigateTo({
        url: `/pages/itemdetail/saledetail?id=${orderId}&status=31`
      })
    })
  }

  //拒绝接单
  onRecallHandle(item, status) {
    let isShow = true
    this.setState({
      isShow,
      item,
      crmodal: status,
      modal1: '您确认拒绝接受订单吗？'
    })
  }
  refuseSaleOrder(orderId) {
    // 拒绝接单
    http.refuseSaleOrder2({ orderId: orderId }).then(res => {
      Taro.redirectTo({
        url: `/pages/carsalesorder/carsalesorder?active=3`
      })
    });
  }
  //关闭模态框
  onClose() {
    let isShow = false
    this.setState({
      isShow
    })
  }
  //模态框确认按钮
  async onLastHandle() {      //crmodal:1接收  2拒绝
    let { crmodal, item, refundOrderId } = this.state
    this.onClose()
    if (crmodal === '1') {
      this.confirmSaleOrder(item.id)

    }
    if (crmodal === '2') {
      this.refuseSaleOrder(item.id)
    }
    if (crmodal === '3') { // 确认退款
      const { infoData, bodyData, signData } = await http.withdrawalOfConsent(refundOrderId)
      this.setState({ infoData, bodyData, signData }, () => {
        this.refs.submit.click()
      })
    }
  }
  //上传合同
  onHandleDownload(item) {
    Taro.navigateTo({
      url: `/pages/caruploadinfo/caruploadinfo?id=${item.id}`
    })
  }
  //下载资料
  onHandleUpload(item) {
    http.clcgTemplate(item.id).then((res, urls) => {
      // 下载合同接口
      const a = document.createElement('a');
      const url = urls;
      const filename = '车辆采购合同下载.zip';
      a.href = url;
      a.download = filename;
      a.click();
    })
  }

  getStatus(status) {
    return {
      $21: `待接单`,
      $31: `待上传`,
      $32: `待买家确认`,
      $33: `待核实`,
      $41: `交易成功`,
      $42: `已拒接`,
      $43: `已撤回`,
      $44: `已超时`,
      $45: `交易异常`,
      $49: `申请退款`,
    }[`$${status}`]
  }

  // 确认退款
  handleConfirmRefund(orderId) {
    http.withdrawOrder2(orderId).then(res => {
      if (res === 0) {
        Taro.showToast({
          title: "该订单已退款",
          icon: "none",
          duration: 800
        });
        setTimeout(() => {
          Taro.reLaunch({
            url: "/pages/carsalesorder/carsalesorder?active=3"
          });
        }, 800);
      } else {
        this.setState({
          isShow: true,
          crmodal: "3",
          refundOrderId: orderId,
          modal1: '您是否确认退款？'
        })
      }
    })
  }

  render() {
    const tabList = [{ title: '待接单' }, { title: '上传合同' }, { title: '已完结' }, { title: '确认退款' }]
    const {
      active,
      list,
      isShow,
      modal1,
      scrollStyle,
      footerStatus,
      infoData,
      bodyData,
      signData,
    } = this.state
    return (
      <View className='b_carsalesorder'>
        <DNavBar title={'售车订单'} className='b_carsalesorder_nav'></DNavBar>
        <View className='b_carsalesorder__box'>
          <View className='b_carsalesorder__content'>
            <AtTabs current={active} tabList={tabList} onClick={this.handleClick.bind(this)}>
              <AtTabsPane>
                <ScrollView
                  scrollY
                  scrollWithAnimation
                  lowerThreshold='20'
                  style={`height:500px`}
                  onScrollToLower={this.onScroll}>
                  {
                    list && list.map((item, i) => {
                      return <DCarorder
                        key={i}
                        order={item.orNo}
                        status={this.getStatus(item.orStatus)}
                        list={[item.orCarModel]}
                        flag={[item.orCarSourceType, item.orCarEmissionStd, '外观颜色:', item.orCarOutColor]}
                        tipmoney={item.orCarGuiPrice}
                        addre={item.orSaleComp}
                        total={item.orCount}
                        money={item.orTotalPrice}
                        firstText={item.orStatus === '21' && '接受订单'}
                        lastText={item.orStatus === '21' && '拒绝接单'}
                        onHandleDetail={this.handlerprops.bind(this, item)}
                        onHandleFirst={this.onhandleAccept.bind(this, item, '1')}
                        onHandleLast={this.onRecallHandle.bind(this, item, '2')}
                      >
                      </DCarorder>
                    })
                  }
                  {
                    footerStatus && <View className='b_carsalesorder__more'>暂无更多</View>
                  }
                </ScrollView>
              </AtTabsPane>

              <AtTabsPane>
                <ScrollView
                  scrollY
                  scrollWithAnimation
                  lowerThreshold='20'
                  style={`height:${scrollStyle - 50}PX`}
                  onScrollToLower={this.onScroll}>
                  {
                    list && list.map((item, i) => {
                      return <DCarorder
                        key={i}
                        order={item.orNo}
                        status={this.getStatus(item.orStatus)}
                        list={[item.orCarModel]}
                        flag={[item.orCarSourceType, item.orCarEmissionStd, '外观颜色:', item.orCarOutColor]}
                        tipmoney={item.orCarGuiPrice}
                        addre={item.orSaleComp}
                        total={item.orCount}
                        money={item.orTotalPrice}
                        firstText={item.orStatus === '31' && '上传合同'}

                        onHandleDetail={this.handlerprops.bind(this, item)}
                        onHandleFirst={this.onHandleDownload.bind(this, item)}
                        onHandleLast={this.onHandleUpload.bind(this, item)}
                      >
                      </DCarorder>
                    })
                  }
                  {
                    footerStatus && <View className='b_carsalesorder__more'>暂无更多</View>
                  }
                </ScrollView>
              </AtTabsPane>
              <AtTabsPane>
                <ScrollView
                  scrollY
                  scrollWithAnimation
                  lowerThreshold='20'
                  style={`height:${scrollStyle - 50}PX`}
                  onScrollToLower={this.onScroll}>
                  {
                    list && list.map((item, i) => {
                      return <DCarorder
                        key={i}
                        order={item.orNo}
                        status={this.getStatus(item.orStatus)}
                        list={[item.orCarModel]}
                        flag={[item.orCarSourceType, item.orCarEmissionStd, '外观颜色:', item.orCarOutColor]}
                        tipmoney={item.orCarGuiPrice}
                        addre={item.orSaleComp}
                        total={item.orCount}
                        money={item.orTotalPrice}
                        firstText={'查看订单'}
                        onHandleDetail={this.handlerprops.bind(this, item)}
                        onHandleFirst={this.handlerprops.bind(this, item)}
                      >
                      </DCarorder>
                    })
                  }
                  {
                    footerStatus && <View className='b_carsalesorder__more'>暂无更多</View>
                  }
                </ScrollView>
              </AtTabsPane>
              <AtTabsPane>
                <ScrollView
                  scrollY
                  scrollWithAnimation
                  lowerThreshold='20'
                  style={`height:${scrollStyle - 50}PX`}
                >
                  {
                    list && list.map((item, i) => {
                      return <DCarorder
                        key={i}
                        order={item.orNo}
                        status={this.getStatus(item.orStatus)}
                        list={[item.orCarModel]}
                        flag={[item.orCarSourceType, item.orCarEmissionStd, '外观颜色:', item.orCarOutColor]}
                        tipmoney={item.orCarGuiPrice}
                        addre={item.orSaleComp}
                        total={item.orCount}
                        money={item.orTotalPrice}
                        firstText={item.orStatus === '49' && '确认退款'}
                        onHandleFirst={this.handleConfirmRefund.bind(this, item.id)}
                        onHandleDetail={this.handlerprops.bind(this, item)}
                      >
                      </DCarorder>
                    })
                  }
                  {
                    footerStatus && <View className='b_carsalesorder__more'>暂无更多</View>
                  }
                </ScrollView>
              </AtTabsPane>
            </AtTabs>
          </View>
          {
            list.length === 0 && <DItemError></DItemError>
          }
          <DModal
            isShow={isShow}
            title='提示'
            text={modal1}
            firstbtn='取消'
            lastbtn='确认'
            onFirst={this.onClose.bind(this)}
            onCancel={this.onClose.bind(this)}
            onLast={this.onLastHandle.bind(this)}
          ></DModal>
        </View>

        {/* 跳转龙存管页面 */}
        <form action={conf.fromURL} method="post">
          <input type="hidden" name="INFO" value={infoData} />
          <input type="hidden" name="CONTENTTYPE" value="json" />
          <input type="hidden" name="charset" value="GBK" />
          <input type="hidden" name="BODY" value={bodyData} />
          <input type="hidden" name="SIGN" value={signData} />
          <input type="submit" ref="submit" value="Submit" style={{ opacity: 0, width: 0, height: 0 }} />
        </form>
      </View>

    )
  }
}
